"""
@Author：十
@Time：2024/8/5 11:29
@FileName：site.py
@Description：选定检测站点实现
"""
import sqlite3
import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication, QTableWidgetItem, QMessageBox

from UI.site import Ui_Form
import EdgeIOT

sitePMS = ''
lineName = ''


class SiteWindow(QWidget, Ui_Form):
    # 获取测试数据
    Signal_Get_Test_Data = pyqtSignal(object)

    def __init__(self, parent=None):
        super(SiteWindow, self).__init__()

        self.parent = parent

        self.devicePMS = None

        self.setupUi(self)

        # self.pushButton.setEnabled(False)

        self.pushButton.clicked.connect(self.Confirm)

        self.Signal_Get_Test_Data.connect(self.GetTestData)

        # 测试数据
        self.test_data = None

    # 从主窗口获取测试数据
    def GetTestData(self, test_data):
        # print(test_data)
        self.test_data = test_data

    def Confirm(self):
        try:
            selected_row = self.tableWidget.currentRow()
            # print(selected_row)
            if selected_row > 0:
                device_name = self.tableWidget.item(selected_row, 0).text()
                self.devicePMS = self.tableWidget.item(selected_row, 1).text()
                print(device_name, self.devicePMS)
                # 上传数据要先订阅，在上传
                if EdgeIOT.Subscribe_device():
                    # 站点的PMS获取edgeID
                    EdgeIOT.Publish_EventLinkUP(sitePMS, lineName)

        except Exception as e:
            print('上传数据错误：', e)

    # 获取的报文数据进行展示和处理
    def MessageReceived(self, messages):
        global sitePMS
        global lineName
        device_type = messages.get('type')
        # print(type)
        try:
            if device_type == 'CMD_GET_LINKEDDEVICE':  # 被监测设备标识查询的返回
                objOrders = messages.get('param')[0]['objOrder']
                sitePMS = messages.get('param')[0]['pmsId']
                lineName = messages.get('param')[0]['lineName']
                # print(sitePMS, lineName)
                self.tableWidget.setRowCount(len(objOrders))
                # 设备的PMS放入表格
                for row, item in enumerate(objOrders):
                    name_item = QTableWidgetItem(item['name'])
                    pms_id_item = QTableWidgetItem(item['pmsId'])
                    self.tableWidget.setItem(row, 0, name_item)
                    self.tableWidget.setItem(row, 1, pms_id_item)
            elif device_type == 'EVENT_LINKUP':  # 获取edgeId的返回
                edgeId = messages.get('param')['edgeId']
                # print(edgeId)

                self.ReportData(edgeId, self.devicePMS)
            elif device_type == 'CMD_REPORTDATA':  # 数据上报的返回
                # QMessageBox.about(self, '成功', '上传数据成功')
                print('数据上传成功')
                # TODO: 在数据库中将已经上传的数据的has_report字段置1
                # 数据库的处理传到主函数，在回调函数中无法获取之前传过来的设备数据
                self.UpdateReport()

        except Exception as e:
            print('报文添加到table错误：', e)

    # 上传数据
    def ReportData(self, edgeId, devicePMS):
        try:
            # print(edgeId, devicePMS)
            # print('类型：', type(edgeId), type(devicePMS))
            EdgeIOT.Subscribe_service_edgeID(edgeId)
            if EdgeIOT.Publish_ReportData(edgeId, devicePMS, self.test_data):
                # TODO：QMessageBox会是程序崩溃
                # QMessageBox.about(self, '成功', '数据上传成功')
                print('数据上传成功')
                # self.close()
        except Exception as e:
            print('数据返回或弹出弹窗失败：', e)

    # 接收到上传返回报文的成功信息后，将has_report字段置1
    def UpdateReport(self):
        try:
            # TODO： 获取仪器名称要从传过来的数据里面获取
            instrument = self.parent.parent.label_Instrument.text()
            print('设备名：', instrument)
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()

            if instrument == '直流电阻测试仪':
                cursor.execute(("UPDATE dcr_data SET has_report = 1 WHERE test_time = ? AND test_mode = ? AND test_electricity = ? AND resistor_AO = ? AND resistor_BO = ? AND "
                                "resistor_CO = ? AND maximum_unbalance_rate = ? AND has_delete = 0 AND has_report = 0"), tuple(self.test_data))

            connection.commit()
            connection.close()

        except sqlite3.Error as e:
            print("上传数据库操作错误:", e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = SiteWindow()
    mainWindow.show()
    sys.exit(app.exec_())
